
<template>
  <div class="AddOrUpdate_main add_container column_three">
    <div class="main_main">
      <el-form ref="form" :model="formData" :rules="rules" :inline="true">
        <el-form-item label="盘点单号" prop="checkCode">
          <CodeRuleInput :band-value.sync="formData.checkCode" table-name="wms_check" column-name="check_code" :is-edit="id" />
        </el-form-item>
        <el-form-item label="仓库" prop="warehouseId">
          <div v-if="id&&formData.status!=0" class="readonly_style">
            <el-input
              v-model="formData.warehouseName"
              readonly
            />
          </div>
          <el-select v-else v-model="formData.warehouseId" filterable clearable @change="changeWarehouse">
            <el-option
              v-for="item in statusOptionsWarehouse"
              :key="item.id"
              :label="item.warehouseName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="盘点方式" prop="checkTypeId">
          <div v-if="id" class="readonly_style">
            <el-input
              v-model="formData.checkTypeName"
              readonly
            />
          </div>
          <el-select v-else v-model="formData.checkTypeId" filterable clearable @change="changeType">
            <el-option label="普通盘点" value="0" />
            <el-option label="扫码盘点" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="盘点人员">
          <div v-if="id&&formData.status!=0" class="readonly_style">
            <el-input
              v-model="formData.checkByName"
              readonly
            />
          </div>
          <el-select v-else v-model="formData.checkBy" filterable clearable>
            <el-option
              v-for="item in userList"
              :key="item.userId"
              :label="item.realName"
              :value="item.userId"
              placeholder="请选择"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="盘点日期" class="time">
          <div v-if="id&&formData.status!=0" class="readonly_style">
            <el-input
              v-model="formData.checkTime"
              readonly
            />
          </div>
          <el-date-picker
            v-else
            v-model="formData.checkTime"
            type="date"
            value-format="yyyy-MM-dd"
            format="yyyy-MM-dd"
            placeholder="请选择"
            :editable="false"
          />
        </el-form-item>
        <el-form-item label="附件" class="double">
          <FileManageFull
            :file-names="formData.fileName"
            :file-real-names="formData.fileRealName"
            :file-urls="formData.url"
            :row-index="1"
            @fileName="setFileName"
          />
        </el-form-item>
        <el-form-item label="备注" class="double">
          <el-input
            v-model="formData.remark"
            maxlength="200"
            show-word-limit
            :disabled="id&&formData.status!=0"
            type="textarea"
            placeholder="请输入"
          />
        </el-form-item>
      </el-form>
      <div class="formItem_header">
        物料明细
        <div class="formItem_header_operate">
          <a class="formItem_header_operate_item" @click="importData">
            <svg-icon icon-class="导入" />
            <div class="item_name">导入</div>
          </a>
          <a class="formItem_header_operate_item" @click="exportData">
            <svg-icon icon-class="导出" />
            <div class="item_name">导出</div>
          </a>
        </div>
      </div>
      <div ref="table_container2" class="table_container addRow_table">
        <el-table
          ref="table"
          :data="stockList"
          stripe
          border
          :height="tableHeight"
          :header-cell-class-name="headerCellClassName"
          :show-overflow-tooltip="true"
        >
          <el-table-column label="物料编码" min-width="120" prop="materialCode" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.materialCode }}</span>
            </template>
          </el-table-column>
          <el-table-column label="物料名称" min-width="100" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.materialName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="规格型号" min-width="100" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.materialModel }}</span>
            </template>
          </el-table-column>
          <el-table-column label="物料分类" min-width="100" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.materialTypeName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="物料单位" min-width="100">
            <template slot-scope="scope">
              <span>{{ scope.row.materialUnitName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="批号" min-width="100">
            <template slot-scope="scope">
              <span>{{ scope.row.palletBatchCode }}</span>
            </template>
          </el-table-column>
          <el-table-column label="库存数量" :min-width="SETTINGS.settings_decimalDigits_length">
            <template slot-scope="scope">
              <span>{{ scope.row.stockNum }}</span>
            </template>
          </el-table-column>
          <el-table-column label="实盘数量" fixed="right" :min-width="SETTINGS.settings_decimalDigits_length" prop="realNum">
            <template slot-scope="scope">
              <el-input v-model="scope.row.realNum" placeholder="请输入" clearable @input="changeReal($event,scope.row,scope.$index)" />
            </template>
          </el-table-column>
          <el-table-column label="差异数量" :min-width="SETTINGS.settings_decimalDigits_length" prop="diffNum">
            <template slot-scope="scope">
              <span>{{ scope.row.diffNum }}</span>
            </template>
          </el-table-column>
          <el-table-column label="备注" min-width="200">
            <template slot-scope="scope">
              <el-input v-model="scope.row.remark" placeholder="请输入" clearable />
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="main_bottom">
      <el-button type="cancel" @click.stop="cancel">取消</el-button>
      <el-button @click.stop="save">保存</el-button>
      <el-button @click.stop="onSubmit">提交</el-button>
    </div>
    <input ref="upload" type="file" style="display: none" @change="handleFileChange">
  </div>
</template>

<script>
// import { getUserList, importMethod } from '@/api/equipmentManage/sparePart/inventory'
import { list as getUserList } from '@/api/system/user'
import { addOrUpdate, getInfo, getAllBatchByWarehouseId, importMethod } from '@/api/warehouseManagement/warehouseCheck'
// import ImportData from '@/components/JLink/common/ImportData'
import firmOffer from './firmOffer.vue'
import { greaterThanZero } from '@/api/warehouseManagement/warehouseModeling'
import { mapGetters } from 'vuex'
import moment from 'moment'
import { export2Excel } from '@/utils/util'
import Big from 'big.js'
export default {
  name: 'AddOrUpdate',
  props: {
    layerid: {},
    id: {},
    defaultValue: {}
  },
  data() {
    return {
      formData: {
        checkCode: '',
        warehouseName: '',
        warehouseId: '',
        checkBy: '',
        checkTime: '',
        fileName: '',
        fileRealName: '',
        url: '',
        remark: '',
        status: '0',
        checkByName: '',
        checkTypeId: '0',
        checkTypeName: '',
        id: ''
      },
      columns: [
        { label: 'id', prop: 'id' },
        { label: '物料id', prop: 'materialId' },
        { label: '库存id', prop: 'stockDetailsId' },
        { label: '物料编码', prop: 'materialCode' },
        { label: '物料名称', prop: 'materialName' },
        { label: '规格型号', prop: 'materialModel' },
        { label: '物料分类', prop: 'materialTypeName' },
        { label: '物料单位', prop: 'materialUnitName' },
        { label: '批号', prop: 'palletBatchCode' },
        { label: '库存数量', prop: 'stockNum' },
        { label: '实盘数量', prop: 'realNum' },
        // { label: '差异数量', prop: 'diffNum' },
        { label: '备注', prop: 'remark' }
      ],
      mainId: 'id',
      pageData: {
        pageNum: 1,
        pageSize: 20,
        orderByColumn: 'updateTime',
        isAsc: 'desc'
      },
      selectionsAll: [],
      pageId: '盘点物料明细',
      selectData: [],
      selectionsAll1: [],
      tableData: [],
      tableHeight: '400',
      num: 1,
      roleOptions: [],
      rules: {
        checkCode: [
          { required: true, message: '盘点单号不能为空', trigger: 'blur' }
        ],
        warehouseId: [
          { required: true, message: '仓库不能为空', trigger: 'change' }
        ],
        checkTypeId: [
          { required: true, message: '盘点方式不能为空', trigger: 'change' }
        ]
      },
      normalList: [],
      objectData: [],
      userList: [],
      stockList: [],
      statusOptionsWarehouse: []
    }
  },
  computed: {
    ...mapGetters([
      'userId'
    ])
  },
  created() {
    if (!this.id) { // 没有id就是新增
      Object.keys(this.defaultValue).forEach(key => { // 给右边数据赋值
        this.formData[key] = this.defaultValue[key]
      })
    } else { // 有id就是编辑
      this.getInfo()
    }
  },
  mounted() {
    this.getList()
    this.laodUserList()
    this.formData.checkBy = this.userId
    this.formData.checkTime = moment(new Date()).format('YYYY-MM-DD HH:mm')
  },
  methods: {
    setFileName(...data) {
      this.$set(this.formData, 'fileName', data[0])
      this.$set(this.formData, 'fileRealName', data[1])
      this.$set(this.formData, 'url', data[2])
    },
    headerCellClassName(data) {
      if (['realNum'].indexOf(data.column.property) != -1) {
        return 'column_bt'
      }
    },
    firmOffer() {
      this.$layer.iframe({// 弹框
        content: {
          content: firmOffer, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {}// props
        },
        area: ['880px', '700px'],
        title: '实盘数量', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    changeReal(e, row, index) {
      if (row.realNum) {
        this.stockList[index].diffNum = new Big(this.stockList[index].realNum).minus(this.stockList[index].stockNum).toString()
      } else {
        this.stockList[index].diffNum = ''
      }
    },
    selectionChange1(rows) {
      this.selectionsAll1 = rows
    },
    changeType(e) {
      if (e == '1') {
        this.stockList = []
      } else {
        this.changeWarehouse(this.formData.warehouseId)
        this.stockList = this.normalList
      }
    },
    importData() { // 导入
      // this.$layer.iframe({// 弹框
      //   content: {
      //     content: ImportData, // 传递的组件对象
      //     parent: this, // 当前的vue对象
      //     data: {}// props
      //   },
      //   area: ['440px', '200px'],
      //   title: '导入数据', // 标题
      //   shadeClose: false // 点击遮罩是否关闭
      // })
      this.$refs.upload.click()
    },
    importMethod(files) { // 导入接口
      importMethod(files).then(res => {
        console.log(res)
        if (res.data) {
          this.stockList = []
          this.$nextTick(() => {
            res.data.forEach(item => {
              this.stockList.push(item)
            })
          })
        }
      })
    },
    addRow(row) {
      // const row2 = [
      //   {
      //     spareCode: row.spareCode || '',
      //     spareName: row.spareName || '',
      //     spareModel: row.spareModel || '',
      //     batch: row.batch || '',
      //     supplierName: row.supplierName || '',
      //     numberUnitLabel: row.numberUnitLabel || '',
      //     number: row.number || '',
      //     realNum: row.realNum || '',
      //     diffNum: row.diffNum || '',
      //     deviceSpareWarehouseName: row.deviceSpareWarehouseName || '',
      //     deviceSpareStandingBookId: row.deviceSpareStandingBookId || '',
      //     deviceSpareWarehouseId: row.deviceSpareWarehouseId || ''
      //   }
      // ]
      this.stockList.push(...row)
    },
    exportData() {
      export2Excel(this.columns, this.stockList, this.pageId)
    },
    // // 查询所有仓库
    // loadWarehouseList() {
    //   listIsNotEmpty().then(res => {
    //     res.data.forEach(item => {
    //       item['value'] = item.id
    //       item['label'] = item.name
    //     })
    //     this.statusOptionsWarehouse = res.data
    //   })
    // },
    // 查询所有人员
    laodUserList() {
      getUserList({
        companyId: this.$store.state.companyId
      }).then(res => {
        console.log(res)
        this.userList = res.data
      })
    },
    // 切换仓库查询库存
    changeWarehouse(e) {
      if (e) {
        this.loadgetBatchByBookIdAndWarehouseId(e)
      } else {
        this.stockList = []
      }
    },
    // 查询仓库下的库存
    loadgetBatchByBookIdAndWarehouseId(id) {
      if (this.formData.checkTypeId == '0') {
        getAllBatchByWarehouseId(id).then(res => {
          res.data.map(ele => {
            ele['realNum'] = ''
            ele['diffNum'] = ''
            ele.stockDetailsId = ele.id
            return ele
          })
          this.stockList = res.data
        })
      } else {
        this.stockList = []
      }

      // this.normalList = res.data
      // if (this.formData.checkTypeId == '0') {
      //   this.stockList = this.normalList
      // }
    },
    getList() {
      greaterThanZero({ ...this.pageData, greaterThanZero: '1' }).then(res => {
        this.statusOptionsWarehouse = res.data
      })
    },
    getInfo() {
      getInfo(this.id).then(res => {
        Object.keys(this.formData).forEach(key => { // 给右边数据赋值
          this.formData[key] = res.data[key]
        })
        this.stockList = res.data.details
      })
    },
    //  保存
    save() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (!this.formData.id) {
            this.stockList.forEach(ele => {
              delete ele.id
            })
          }
          if (this.stockList.some(ele => ele.realNum)) {
            this.formData.status = '1'
          } else {
            this.formData.status = '0'
          }
          if (this.stockList.filter(item => item.realNum && !this.SETTINGS.reg_zero.test(item.realNum)).length > 0) {
            this.$message.warning('实盘数量未正确填写')
            return
          }

          addOrUpdate({
            ...this.formData,
            details: this.stockList
          }).then(res => {
            this.$message({
              message: res.msg,
              type: 'success'
            })
            this.$layer.close(this.layerid) // 关闭弹框
            this.$parent.refresh() // 调用父组件的刷新方法
          })
        }
      })
    },
    // 提交
    onSubmit() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.stockList.filter(item => !item.realNum).length > 0) {
            this.$message.warning('实盘数量不能为空')
            return
          } else if (this.stockList.filter(item => !this.SETTINGS.reg_zero.test(item.realNum)).length > 0) {
            this.$message.warning('实盘数量填写不正确')
            return
          }
          if (!this.formData.id) {
            this.stockList.forEach(ele => {
              delete ele.id
            })
          }
          this.formData.status = '2'
          addOrUpdate({
            ...this.formData,
            details: this.stockList
          }).then(res => {
            this.$message({
              message: res.msg,
              type: 'success'
            })
            this.$layer.close(this.layerid) // 关闭弹框
            this.$parent.refresh() // 调用父组件的刷新方法
          })
        }
      })
    },
    cancel() {
      this.$layer.close(this.layerid)// 关闭弹框
    },
    removeRow(index) {
      this.tableData.splice(index, 1)
    },
    handleFileChange(e) {
      if (!e.target.files) {
        return
      }
      const files = e.target.files
      this.importMethod(files)
    }
  }
}
</script>

<style lang="less" scoped>

// .formItem_header{
//   justify-content: flex-end !important;
//   align-items: flex-start !important;
//   height: 40px !important;
// }
.readonly_style{
  /deep/ .el-input__inner{
    background-color: #f5f7fa;
    border-color: #dfe4ed;
    color: #c0c4cc;
  }
}
</style>
